/**
 *    @file       domainparse.cpp
 *
 *    @brief      
 *    @details
 *
 *    @version    1.0
 *    @date       12/29/2012 03:35:34 PM
 *
 *    @author     Theophilus (), wangtf418@gmail.com
 */
#include "domainparse.h"
#include "toolkit.h"

std::map<std::string, domain_ip> domainparse::m_domain;
threadmutex domainparse::m_lock;

domainparse::domainparse()
{

}

domainparse::~domainparse()
{

}

bf_int_t domainparse::parse_domain(const std::string &domain, domain_ip &ret_out, bf_int_t reparse_interval /* = BF_PARSE_DOMAIN_INTERVAL */)
{
	lockhelper helper(&m_lock);
	std::map<std::string, domain_ip>::iterator itr = m_domain.find(domain);
	if (itr == m_domain.end() || time(NULL) - itr->second.m_updatetime >= reparse_interval)
	{
		bf_int_t ret = toolkit::parsedomain(domain, ret_out.m_inaddr_list);
		if (ret == BF_OK)
		{
			std::vector<bf_uint32_t>::iterator itr_list = ret_out.m_inaddr_list.begin();
			for (; itr_list != ret_out.m_inaddr_list.end(); itr_list ++)
			{
				ret_out.m_strip_list.push_back(toolkit::inaddr2str(*itr_list));
			}
			ret_out.m_updatetime = time(NULL);
			m_domain[domain] = ret_out;
			return BF_OK;
		}
		else
		{
			return BF_ERROR;
		}
	}
	ret_out = m_domain[domain];
	return BF_OK;
}


bf_int_t domainparse::parse_domain(const std::string &domain, bf_uint32_t &inaddr_out, bf_int_t reparse_interval /* = BF_PARSE_DOMAIN_INTERVAL */)
{
	toolkit::srand();
	domain_ip domainip_out;
	bf_int_t ret = parse_domain(domain, domainip_out, reparse_interval);
	if (ret != BF_OK)
	{
		return BF_ERROR;
	}
	if (domainip_out.m_inaddr_list.size() <= 0)
	{
		return BF_ERROR;
	}
	inaddr_out = domainip_out.m_inaddr_list[rand() % domainip_out.m_inaddr_list.size()];
	return BF_OK;
}

bf_int_t domainparse::parse_domain(const std::string &domain, std::string &ip_out, bf_int_t reparse_interval /* = BF_PARSE_DOMAIN_INTERVAL */)
{
	toolkit::srand();
	domain_ip domainip_out;
	bf_int_t ret = parse_domain(domain, domainip_out, reparse_interval);
	if (ret != BF_OK)
	{
		return BF_ERROR;
	}
	if (domainip_out.m_strip_list.size() <= 0)
	{
		return BF_ERROR;
	}
	ip_out = domainip_out.m_strip_list[rand() % domainip_out.m_strip_list.size()];
	return BF_OK;
}



